package com.nbcio.modules.estar.zz.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nbcio.modules.estar.apithird.service.IEstarThirdService;
import com.nbcio.modules.flowable.apithird.entity.SysUser;
import com.nbcio.modules.im.domain.ImChatGroup;
import com.nbcio.modules.im.service.IImChatGroupService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.nbcio.modules.estar.zz.entity.ZzImGroup;
import com.nbcio.modules.estar.zz.vo.ZzImGroupPage;
import com.nbcio.modules.estar.zz.service.IZzImGroupService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


 /**
 * @Description: 群聊表
 * @Author: nbacheng
 * @Date:   2024-11-27
 * @Version: V1.0
 */
@Api(tags="群聊表")
@RestController
@RequestMapping("/zz/zzImGroup")
@Slf4j
public class ZzImGroupController {
	@Autowired
	private IZzImGroupService zzImGroupService;

	@Autowired
	private IImChatGroupService imChatGroupService;

	@Resource
	private IEstarThirdService iEstarThirdService;

	//zhengzao:用于生成群聊时的头像
	public static final String IM_CHAT_GROUP_AVATAR_DEPT="/temp/depart-chat-group.png";
	public static final String IM_CHAT_GROUP_AVATAR_NORMAL="/temp/normal_chat_group.png";
	/**
	 * 分页列表查询
	 *
	 * @param zzImGroup
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "群聊表-分页列表查询")
	@ApiOperation(value="群聊表-分页列表查询", notes="群聊表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZzImGroup zzImGroup,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZzImGroup> queryWrapper = QueryGenerator.initQueryWrapper(zzImGroup, req.getParameterMap());
		//zhengzao 只有admin账户才能看到所有数据，其他人只能看自己创建的 - start
		SysUser curUser = iEstarThirdService.getLoginUser();
		if(!curUser.getUsername().equals("admin")){
			queryWrapper.eq("create_by",curUser.getUsername());
		}
		//zhengzao 只有admin账户才能看到所有数据，其他人只能看自己创建的 - end
		Page<ZzImGroup> page = new Page<ZzImGroup>(pageNo, pageSize);
		IPage<ZzImGroup> pageList = zzImGroupService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param zzImGroupPage
	 * @return
	 */
	@AutoLog(value = "群聊表-添加")
	@ApiOperation(value="群聊表-添加", notes="群聊表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZzImGroupPage zzImGroupPage) {
		ZzImGroup zzImGroup = new ZzImGroup();
		BeanUtils.copyProperties(zzImGroupPage, zzImGroup);
		//zhengzao 根据客户需求，操作者自己默认加入群聊 - start
		String idStr = zzImGroup.getGroupUsers();
		if(idStr.indexOf(zzImGroup.getCreateBy())==-1){
			idStr += ","+zzImGroup.getCreateBy();
			zzImGroup.setGroupUsers(idStr);
		}
		//zhengzao 根据客户需求，操作者自己默认加入群聊 - end
		zzImGroupService.saveMain(zzImGroup);
		ImChatGroup imChatGroup = new ImChatGroup();
		imChatGroup.setId(zzImGroup.getId());//这一步要验证是否有ID
		imChatGroup.setName(zzImGroup.getGroupName());
		imChatGroup.setMaster(zzImGroup.getCreateBy());
		imChatGroup.setAvatar((zzImGroup.getGroupAvatar()==null?IM_CHAT_GROUP_AVATAR_NORMAL: zzImGroup.getGroupAvatar()));

		imChatGroupService.addGroupWithUsernames(imChatGroup,zzImGroup.getGroupUsers());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param zzImGroupPage
	 * @return
	 */
	@AutoLog(value = "群聊表-编辑")
	@ApiOperation(value="群聊表-编辑", notes="群聊表-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<?> edit(@RequestBody ZzImGroupPage zzImGroupPage) {
		ZzImGroup zzImGroup = new ZzImGroup();
		BeanUtils.copyProperties(zzImGroupPage, zzImGroup);
		ZzImGroup zzImGroupEntity = zzImGroupService.getById(zzImGroup.getId());
		if(zzImGroupEntity==null) {
			return Result.error("未找到对应数据");
		}
		//zhengzao 根据客户需求，强制操作者自己默认加入群聊 - start
		String idStr = zzImGroup.getGroupUsers();
		if(idStr.indexOf(zzImGroup.getCreateBy())==-1){
			idStr += ","+zzImGroup.getCreateBy();
			zzImGroup.setGroupUsers(idStr);
		}
		//zhengzao 根据客户需求，强制操作者自己默认加入群聊 - end
		zzImGroupService.updateMain(zzImGroup);
		ImChatGroup imChatGroup = new ImChatGroup();
		imChatGroup.setId(zzImGroup.getId());//这一步要验证是否有ID
		imChatGroup.setName(zzImGroup.getGroupName());
		imChatGroup.setMaster(zzImGroup.getCreateBy());
		imChatGroup.setAvatar(zzImGroup.getGroupAvatar());
		imChatGroupService.editGroupWithUsernames(imChatGroup,zzImGroup.getGroupUsers());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "群聊表-通过id删除")
	@ApiOperation(value="群聊表-通过id删除", notes="群聊表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		ImChatGroup imChatGroup = new ImChatGroup();
		ZzImGroup zzImGroup = zzImGroupService.getById(id);
		imChatGroup.setId(zzImGroup.getId());//这一步要验证是否有ID
		zzImGroupService.delMain(id);
		imChatGroupService.delGroupWithUsernames(imChatGroup,zzImGroup.getGroupUsers());
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "群聊表-批量删除")
	@ApiOperation(value="群聊表-批量删除", notes="群聊表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zzImGroupService.delBatchMain(Arrays.asList(ids.split(",")));
		imChatGroupService.batchDelGroup(ids);
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "群聊表-通过id查询")
	@ApiOperation(value="群聊表-通过id查询", notes="群聊表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ZzImGroup zzImGroup = zzImGroupService.getById(id);
		if(zzImGroup==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(zzImGroup);

	}
	

    /**
    * 导出excel
    *
    * @param request
    * @param zzImGroup
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZzImGroup zzImGroup) {
		SysUser curUser = iEstarThirdService.getLoginUser();
      // Step.1 组装查询条件查询数据
      QueryWrapper<ZzImGroup> queryWrapper = QueryGenerator.initQueryWrapper(zzImGroup, request.getParameterMap());
      //Step.2 获取导出数据
      List<ZzImGroup> queryList = zzImGroupService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<ZzImGroup> zzImGroupList = new ArrayList<ZzImGroup>();
      if(oConvertUtils.isEmpty(selections)) {
          zzImGroupList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          zzImGroupList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ZzImGroupPage> pageList = new ArrayList<ZzImGroupPage>();
      for (ZzImGroup main : zzImGroupList) {
          ZzImGroupPage vo = new ZzImGroupPage();
          BeanUtils.copyProperties(main, vo);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "群聊表列表");
      mv.addObject(NormalExcelConstants.CLASS, ZzImGroupPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("群聊表数据", "导出人:"+curUser.getRealname(), "群聊表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ZzImGroupPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZzImGroupPage.class, params);
              for (ZzImGroupPage page : list) {
                  ZzImGroup po = new ZzImGroup();
                  BeanUtils.copyProperties(page, po);
                  zzImGroupService.saveMain(po);
				  ImChatGroup imChatGroup = new ImChatGroup();
				  imChatGroup.setId(po.getId());
				  imChatGroup.setName(po.getGroupName());
				  imChatGroup.setMaster(po.getCreateBy());
				  imChatGroup.setAvatar((po.getGroupAvatar()==null?IM_CHAT_GROUP_AVATAR_NORMAL: po.getGroupAvatar()));
				  imChatGroupService.addGroupWithUsernames(imChatGroup,po.getGroupUsers());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
